<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\UpdateUserRequest;
use App\Http\Resources\Book as BookCollection;
use App\Http\Resources\WriteInfo;
use App\Models\User;
use App\Http\Resources\User as UserCollection;
use Illuminate\Http\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use Image;

class UsersController extends ApiController
{




    function __construct()
    {

        $this->middleware('auth:api')->only([

            'bookshelf',
            'getWritingInfo',
            'getBooks',
            'update',
            'uploadAvatar',
            'me'

        ]);

    }



    /**
     *
     * @api {post} /users/changePassword 修改用户密码
     * @apiName User change password
     * @apiGroup User
     *
     * @apiParam {String} phone 用户的手机号
     * @apiParam {String} password 需要修改的密码
     * @apiParam {String} code 发送的验证码
     *
     * @apiVersion 1.0.0
     * @apiSampleRequest /api/users/changePassword
     *
     */
    public function changePassword(Request $request){

        $this->validate($request,[
            'phone' => 'required|exists:user',
            'password' => 'required|min:6',
            'code' => 'required|min:5|max:6'

        ]);


        if (! Cache::has($request->phone.'code')){
            return $this->failed('验证失败');
        }

        $cache_code = Cache::get($request->phone.'code');
        $attempts = Cache::get($request->phone.'attempts');

        if ($attempts <= 0){
            Cache::forget($request->phone.'code');
            return $this->failed('失败次数过多，请重新发送验证码');
        }

        Cache::decrement($request->phone.'attempts');

        if ($cache_code != $request->code){

            return $this->failed('验证码不正确');
        }

        $user = User::where('phone',$request->phone)->first();

        $pwd = app('hash')->make($request->password);
        $user->pwd = $pwd;
        $user->save();

        return $this->message('修改成功');

    }

    /**
     *
     * @api {get} /users/:user 获取当前用户信息
     * @apiName User get user
     * @apiGroup User
     *
     * @apiParam {String} user 当前用户的id
     *
     * @apiVersion 1.0.0
     * @apiSampleRequest /api/users/:user
     *
     */
    public function show(User $user){

        return new UserCollection($user);
    }


    public function update(UpdateUserRequest $request,User $user){


        $this->authorize('update',$user);

        $request->update($user);

        return $this->message('修改成功');


    }


    /**
     * @api {get} me/writing 获取个人写作数据
     * @apiName User me writing
     * @apiGroup User
     *
     * @apiHeaderExample {json} Header-Example:
     *  {
     *       "Authorization" : "Bearer {token}"
     *  }
     *
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/me/writing
     */
    public function getWritingInfo(){

        $user = Auth::user();

        return new WriteInfo($user);

    }

    /**
     * @api {get} me/books 获取个人写作数据
     * @apiName User me books
     * @apiGroup User
     *
     * @apiHeaderExample {json} Header-Example:
     *  {
     *       "Authorization" : "Bearer {token}"
     *  }
     *
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/me/books
     */
    public function getBooks(){

        $user = Auth::user();

        return BookCollection::collection($user->books);

    }


    /**
     * @api {get} /me 获取个人信息
     * @apiName User me
     * @apiGroup User
     *
     * @apiHeaderExample {json} Header-Example:
     *  {
     *       "Authorization" : "Bearer {token}"
     *  }
     *
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/me
     */
    public function me(){

        return new  UserCollection(Auth::user());

    }

    /**
     *
     *
     *
     * @api {get} /me/bookshelf 获取个人书架
     * @apiName User me bookshelf
     * @apiGroup User
     *
     * @apiHeaderExample {json} Header-Example:
     *  {
     *       "Authorization" : "Bearer {token}"
     *  }
     *
     * @apiParam {String} [type] 1=>阅读时间排序,2=>更新时间排序
     * @apiParam {String} [limit] 限制的条数
     * @apiParam {String} [page] 当前的页数
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/me/bookshelf
     *
     * @apiSuccessExample {json} Success-Response:
     *       {
     *           "status": "success",
     *           "code": 200,
     *           "data": [
     *               {
     *                   "id": 337,
     *                   "name": "死神的馈赠",
     *                   "cover": "",
     *                   "book_num": "2f189510cdee4239af516d5dde823090",
     *                   "status": 2,
     *                   "introduction": "",
     *                   "author": "指间流年彡",
     *                   "labels": null,
     *                   "last_chapter": null,
     *                   "read_count": 0,
     *                   "collection_counts": 0
     *               }
     *           ],
     *           "pagination": {
     *               "total": 1,
     *               "count": 1,
     *               "perPage": 20,
     *               "currentPage": 1,
     *               "totalPages": 1,
     *               "links": []
     *           }
     *       }
     */
    public function bookshelf(){


        $limit = Input::get('limit') ?: 20;

        $type = Input::get('type') ?: 1;

        $user = Auth::user();


        // 1.阅读时间时间排序
        if ($type == 1){

            $books = $user->shelf()->whereHas('readRecords',function ($query){
                $query->orderBy('created_at','desc');

            },'>=',0)->paginate($limit);


            return BookCollection::collection($books);

        }


        // 2.更新时间排序
        $books = $user->shelf()->orderBy('last_modify_time','desc')->paginate($limit);

        return BookCollection::collection($books);


    }

    /**
     * @api {post} /users/uploadAvatar 上传头像
     * @apiName User upload Avatar
     * @apiGroup User
     *
     * @apiHeaderExample {json} Header-Example:
     *  {
     *       "Authorization" : "Bearer {token}"
     *  }
     *
     * @apiParam {file} image 上传图片
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/users/uploadAvatar
     */
    public function uploadAvatar(Request $request){

        $this->validate($request,[
            'image' => 'required|image'
        ]);

        $file = $request->file('image');

        $image = $file->move('avatar')->getRealPath();

        $img = Image::make($image);
        $img->fit(400);

        $filename = md5(time()).$file->getClientOriginalName();

        $img->save($filename);

        $file = new File(public_path($filename));
        $path = Storage::disk('qcloud')->putFile('avatars', $file);

        $url = Storage::disk('qcloud')->url($path);

        unlink($filename);
        unlink($image);

        return $this->success(compact('url'));

    }


}
